package com.eln.medplayer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
//import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

/**
 * Movie Player.
 * 
 * @author Josh
 *
 */
public class VidList extends Activity implements OnItemClickListener
{
/** Log tag. */
private static final String MEDIA_AUDIO_PATH_1 = new String("/storage/sdcard0/audio lt");
private static final String MEDIA_AUDIO_PATH_2 = new String("/storage/sdcard0/audio en");
private static final String MEDIA_VIDEO_PATH = new String("/storage/sdcard0/video");
private static final String MEDIA_ARTWORK_PATH = new String("/storage/sdcard0/artwork");
private static final String LOG_TAG = "MoviePlayer";
private static int menuOption=0;
ImageButton thumbnailPlay;
private static View progressView;
static RelativeLayout progressLayout;
private static View mainView;
private static MovieListAdaptor movieListAdapter;
private static ArrayList<Movie> movieList;
private static GridView movieListView;


private static ArrayList<listNames> nameList;

/**
 * On create lifecycle method.
 * 
 * @param savedInstanceState saved state.
 * @see Activity#onCreate(Bundle)
 */
@Override
    protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
    RelativeLayout relative = new RelativeLayout(this);
    
    mainView=View.inflate(getBaseContext(),R.layout.movies_list,null);
    relative.addView(mainView);
    
    
   // progressView = View.inflate(getBaseContext(),R.layout.progressbar, null);
   // relative.addView(progressView);
    

   // setContentView(R.layout.movies_list);
    setContentView(relative);
	

	//progressLayout = (RelativeLayout) findViewById(R.id.progressLayout);
	//progressLayout.setVisibility(View.VISIBLE);
	
	Intent i = getIntent();
    menuOption = i.getExtras().getInt("menuOption");

    movieList = new ArrayList<Movie>();
    
    nameList = new ArrayList<listNames>();

    switch (menuOption){
    case 0:getNameList(MEDIA_AUDIO_PATH_1);getListAudioLt();break;
    case 1:getNameList(MEDIA_AUDIO_PATH_2);getListAudioEn();break;
    case 2:getNameList(MEDIA_VIDEO_PATH);getListVideo();break;
    }

    // Define movie list adapter
    movieListAdapter = new MovieListAdaptor(this,movieList);

    // Set list view adapter to movie list adapter
    movieListView = (GridView) findViewById(R.id.movieListView);
    movieListView.setScrollingCacheEnabled(false);
    movieListView.setFastScrollEnabled(true);

    // Set  item click listener
    movieListView.setOnItemClickListener(this);
    
   /* movieListView.setOnScrollListener(new OnScrollListener() { 



        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub

        }

        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
            if(scrollState != SCROLL_STATE_IDLE) {
            	movieListAdapter.isScrolling=true;
            } else {
            	movieListAdapter.isScrolling=false;   
            }

            int first = view.getFirstVisiblePosition(); 
            int count = view.getChildCount(); 

            if (scrollState == SCROLL_STATE_IDLE || (first + count > movieListAdapter.getCount()) ) { 
            	movieListView.invalidateViews(); 
            }

        } 
    }); */
    
    /* movieListView.setOnScrollListener(new OnScrollListener() {

    	   		@Override
				public void onScroll(AbsListView arg0, int arg1, int arg2,
						int arg3) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onScrollStateChanged(AbsListView arg0, int scrollState) {
					// TODO Auto-generated method stub
					if (scrollState != 0){

						((MovieListAdaptor)movieListView.getAdapter()).isScrolling = true;
					}

    	            else {

    	            	((MovieListAdaptor)movieListView.getAdapter()).isScrolling = false;

    	            	((MovieListAdaptor)movieListView.getAdapter()).notifyDataSetChanged();

    	           }
				}

    	   });*/
    
    
	
	/*thumbnailPlay=(ImageButton) findViewById(R.id.btn_thumbnail_play);
	thumbnailPlay.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {

		}
	});*/
    

    thread.start();
    
	//runOnUiThread(new Runnable(){
			//public void run() {
				//movieListView.setAdapter(movieListAdapter);
				//progressLayout.setVisibility(View.INVISIBLE); 
			//}
			
		//});
	
}

Thread thread = new Thread()
{
    @Override
    public void run() {
    	//try {
		//	sleep(2000);
		//} catch (InterruptedException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		//}
    	movieListView.setAdapter(movieListAdapter);
		//progressLayout.setVisibility(View.INVISIBLE); 
    }
};

public void getListVideo(){
	 // Media columns to query
    String[] mediaColumns = {
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.TITLE,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.MIME_TYPE };

    // Thumbnail columns to query
    String[] thumbnailColumns = { MediaStore.Video.Thumbnails.DATA };

    String mediadata=MediaStore.Video.Media.DATA;
    // Query external movie content for selected media columns
    
   /* String folder = MEDIA_VIDEO_PATH;
    folder = folder + "/%";
    String where = Artists._ID + " IN (SELECT " + MediaStore.Video.Media.ARTIST_ID + " FROM audio WHERE " +
    		MediaStore.Video.Media.DATA + " LIKE ?)";
    String[] whereArgs = new String[]{folder};*/
    Cursor mediaCursor = getContentResolver().query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            mediaColumns, MediaStore.Video.Media.DATA+" like '%"+MEDIA_VIDEO_PATH+"%'", null, MediaStore.Video.Media.DATA + " COLLATE LOCALIZED ASC");

            /*managedQuery(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, mediaColumns,
            null, null, null);*/

    // Loop through media results
    if ( (mediaCursor != null) && mediaCursor.moveToFirst() )
    {
        do
        {
            // Get the video id
            int id = mediaCursor.getInt(mediaCursor
                    .getColumnIndex(MediaStore.Video.Media._ID));

            // Get the thumbnail associated with the video
            Cursor thumbnailCursor = getContentResolver().query(
                    MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                    thumbnailColumns, MediaStore.Video.Thumbnails.VIDEO_ID
                        + "=" + id, null, null);

                    /*managedQuery(
                    MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                    thumbnailColumns, MediaStore.Video.Thumbnails.VIDEO_ID
                            + "=" + id, null, null);*/

            // New movie object from the data
            Movie movie = new Movie(mediaCursor, thumbnailCursor,null,nameList);
            Log.d(LOG_TAG, movie.toString());

            // Add to movie list
            File file = new File(movie.getMoviePath());
            if (file.exists()) {
               movieList.add(movie);
            }

        }
        while (mediaCursor.moveToNext());
    }
}

public void getListAudioLt(){
	 // Media columns to query
   String[] mediaColumns = {
           MediaStore.Audio.Media._ID,
           MediaStore.Audio.Media.TITLE,
           MediaStore.Audio.Media.DURATION,
           MediaStore.Audio.Media.DATA,
           MediaStore.Audio.Media.MIME_TYPE,
           MediaStore.Audio.Media.ALBUM_ID };

   // Thumbnail columns to query
   String[] thumbnailColumns = { MediaStore.Audio.Media.ALBUM_ID };

   // Query external movie content for selected media columns
   Cursor mediaCursor = getContentResolver().query(
           MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
           mediaColumns, MediaStore.Audio.Media.DATA+" like '%"+MEDIA_AUDIO_PATH_1+"%'", null,  MediaStore.Audio.Media.DATA + " COLLATE LOCALIZED ASC");
           //mediaColumns, MediaStore.Audio.Media.DATA+" like '%"+MEDIA_AUDIO_PATH_1+"%' and "+ MediaStore.Audio.Media.DATA+" like '%_LT%'", null,  MediaStore.Audio.Media.DATA + " COLLATE LOCALIZED ASC");
   
  /* String folder = MEDIA_AUDIO_PATH;
   folder = folder + "/%";
   String where = MediaStore.Audio.Artists._ID + " IN (SELECT " + MediaStore.Audio.Media.ARTIST_ID + " FROM audio WHERE " +
		   MediaStore.Audio.Media.DATA + " LIKE ?)";
   String[] whereArgs = new String[]{folder};
   Cursor mediaCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mediaColumns,where,whereArgs,null);*/
   /*Cursor mediaCursor  = getContentResolver().query(MediaStore.Audio.Media.Artist.EXTERNAL_CONTENT_URI,
       cols, where, whereArgs, AudioColumns.ARTIST + " COLLATE LOCALIZED ASC");*/
   
   if ( (mediaCursor != null) && mediaCursor.moveToFirst() )
   {
       do
       {
           
           Cursor thumbnailCursor = null;
           String album_id=mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(
        		   MediaStore.Audio.Media.ALBUM_ID));
           // New movie object from the data
           Movie movie = new Movie(mediaCursor, thumbnailCursor,album_id,nameList);
           //Log.d(LOG_TAG, movie.toString());

           // Add to movie list
           movieList.add(movie);

       }
       while (mediaCursor.moveToNext());
   }
}

public void getListAudioEn(){
	 // Media columns to query
  String[] mediaColumns = {
          MediaStore.Audio.Media._ID,
          MediaStore.Audio.Media.TITLE,
          MediaStore.Audio.Media.DURATION,
          MediaStore.Audio.Media.DATA,
          MediaStore.Audio.Media.MIME_TYPE,
          MediaStore.Audio.Media.ALBUM_ID};

  // Thumbnail columns to query
  String[] thumbnailColumns = { MediaStore.Audio.Media.ALBUM_ID };

  // Query external movie content for selected media columns
  Cursor mediaCursor = getContentResolver().query(
          MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
          mediaColumns, MediaStore.Audio.Media.DATA+" like '%"+MEDIA_AUDIO_PATH_2+"%'", null, MediaStore.Audio.Media.DATA + " COLLATE LOCALIZED ASC");
          //mediaColumns, MediaStore.Audio.Media.DATA+" like '%"+MEDIA_AUDIO_PATH_2+"%' and "+ MediaStore.Audio.Media.DATA+" like '%_EN%'", null, MediaStore.Audio.Media.DATA + " COLLATE LOCALIZED ASC");


  if ( (mediaCursor != null) && mediaCursor.moveToFirst() )
  {
      do
      {
          
          Cursor thumbnailCursor = null;

          String album_id=mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(
       		   MediaStore.Audio.Media.ALBUM_ID));
          // New movie object from the data
          Movie movie = new Movie(mediaCursor, thumbnailCursor,album_id,nameList);
          Log.d(LOG_TAG, movie.toString());

          // Add to movie list
          movieList.add(movie);

      }
      while (mediaCursor.moveToNext());
  }
}

public void  getNameList(String path){
	try {
		InputStream is = new FileInputStream(path+"/titles.csv");// getAssets().open();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	                try {
	                    String line;
	                    String name = "";
	                    String title = "";
                        nameList.clear();
                        reader.readLine();
	                    while ((line = reader.readLine()) != null) {

	                        String[] RowData = line.split(",");
	                        name = RowData[0];
	                       // title = RowData[1].substring(1, RowData[1].length()-1).replaceAll("\"", "&quote;").replaceAll("&quote;&quote;", "\"");
	                        if (RowData.length>2){
	                        	title="";
	                        	for(int i=1;i<RowData.length;i++){
	                        		title =title + RowData[i].replaceAll("\"", "&quote;").replaceAll("&quote;&quote;", "\"")+",";
	                        	}
	                        	title=title.substring(0, title.length()-1);
	                        }else{
	                        title = RowData[1].replaceAll("\"", "&quote;").replaceAll("&quote;&quote;", "\"");
	                        }
	                        nameList.add(new listNames(name,title));
	                    }
	                }catch (IOException ex) {
	                    // handle exception
	                }finally {
	                    try {
	                        is.close();
	                    }
	                    catch (IOException e) {
	                        // handle exception
	                    }
	                }
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}




@Override
/*public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_movie_player, menu);
    return true;
}*/

    /**
     * On item click listener.
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        // Gets the selected movie
	
      	
        Movie movie = (Movie) parent.getAdapter().getItem(position);

        // Plays the selected movie
        /* Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse(movie.getMoviePath()), movie.getMimeType());
        startActivity(intent);*/
        
       // Intent intent = new Intent(getApplicationContext(),VidActivity.class);
       // Intent intent = new Intent(this,VidActivity.class);
        Intent intent = new Intent();
        switch (menuOption){
        case 0:intent= new Intent(this, AudActivity.class);break;
        case 1:intent= new Intent(this, AudActivity.class);break;
        case 2:intent= new Intent(this, VidActivity.class);break;
        }
        // Sending songIndex to PlayerActivity
        intent.putExtra("listIndex", position);
        intent.putExtra("menuOption", menuOption);
       // intent.putExtra("movieList",movieList);
        
        intent.putParcelableArrayListExtra("movieList",movieList);
		//setResult(100, intent);
		//finish();
		startActivity(intent);
		VidList.this.overridePendingTransition(
				R.anim.slide_in_right,
				R.anim.slide_out_left
	    		);
		finish();
    }


  @Override
  public void onBackPressed() {
	  Intent intent = new Intent(this, MedPlayer.class);
	  startActivity(intent);
	  VidList.this.overridePendingTransition(
				R.anim.slide_in_left, 
				R.anim.slide_out_right
	    		);
	  finish();
  }

}